package com.pengtu.gsj.service.impl.check.anqsc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.service.check.CheckTableService;
import com.pengtu.gsj.service.check.anqsc.EmergPatSecService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.utils.MathsUtils;

@Service
@Transactional
public class EmergPatSecServiceImpl implements EmergPatSecService{

	@Autowired
	public SystemManageService systemManageService;
	@Autowired
	public CheckTableService checkTableService;
	
	@Override
	public Map<String, Object> getEmergPatSecs(String startTime, String endTime, CheckTable checkTable, String tag) throws Exception {
		List<Attachment> list = new ArrayList<Attachment>();
		List<Object> values = new ArrayList<Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonObject = JSONObject.parseObject(checkTable.getRetrieval());
		double firstScore = Double.parseDouble((String)jsonObject.get("yearFull"));
		double secondScore = Double.parseDouble((String)jsonObject.get("firstStepScore"));
		double thirdScore = Double.parseDouble((String)jsonObject.get("secondStepScore"));
		double tableFull = firstScore + secondScore + thirdScore;
		double percentage = 0; 
		//根据时间、标签查询是否有附件
		list = systemManageService.getCheckAttachments(startTime, endTime, tag);
		// 检查对应的应急预案、储备计划是否有附件，有的话得分，没有就得0分
		if (systemManageService.getCheckAttachmentByTag(startTime, endTime, "yjbt_yjya").size() == 0) {
			firstScore = 0;
		}
		if (systemManageService.getCheckAttachmentByTag(startTime, endTime, "yjbt_cbjh").size() == 0) {
			thirdScore = 0;
		}
		//计算总分
		double total = MathsUtils.formatDouble(MathsUtils.sum(firstScore , secondScore , thirdScore), 1);
		//并算出完善度
		percentage = MathsUtils.divDouble(total*100, tableFull, 2);
		values.add("true");
		//只有当系统完善度和检查得分不相等的情况下才更新数据  避免每次搜索都更新数据
		checkTableService.updateCheckTable(checkTable, percentage, total, tableFull, values);
		map.put("att", list);
		map.put("firstScore", firstScore);
		map.put("secondScore", secondScore);
		map.put("thirdScore", thirdScore);
		map.put("percent", percentage);
		map.put("score", checkTable.getTestFull());
		map.put("percent", percentage);
		map.put("checkTable", checkTable);
		return map;
	}
}
